package com.qiandw

import com.qiandw.security.{MemberAccessDecisionManager, MemberSecurityMetadataSource, MemberUserDetailsService, RestAuthenticationEntryPoint}
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.security.authentication.encoding.Md5PasswordEncoder
import org.springframework.security.config.annotation.ObjectPostProcessor
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder
import org.springframework.security.config.annotation.web.builders.HttpSecurity
import org.springframework.security.config.annotation.web.configuration.{EnableWebSecurity, WebSecurityConfigurerAdapter}
import org.springframework.security.web.access.intercept.FilterSecurityInterceptor

@EnableWebSecurity
class AppSecurityConfig extends WebSecurityConfigurerAdapter {

  @Autowired
  var memberUserDetailsService: MemberUserDetailsService = _

  @Autowired
  var memberAccessDecisionManager: MemberAccessDecisionManager = _

  @Autowired
  var MemberSecurityMetadataSource: MemberSecurityMetadataSource = _

  @Autowired
  var RestAuthenticationEntryPoint: RestAuthenticationEntryPoint = _

  override def configure(auth: AuthenticationManagerBuilder): Unit = {
    auth.inMemoryAuthentication()
//      .withUser("user").password("123456").roles("USER", "ANY")
//      .and()
//      .withUser("admin").password("123456").roles("ADMIN", "USER", "ANY")
      .withUser("user").password("96e79218965eb72c92a549dd5a330112").roles("USER", "ANY")
      .and()
      .withUser("admin").password("96e79218965eb72c92a549dd5a330112").roles("ADMIN", "USER", "ANY")
      .and()
      .passwordEncoder(new Md5PasswordEncoder)

//    auth.userDetailsService(memberUserDetailsService)
//      .passwordEncoder(new Md5PasswordEncoder)
  }

  override def configure(http: HttpSecurity): Unit = {
    http.authorizeRequests()//配置安全策略
      .antMatchers("/", "/home**").permitAll()//定义/请求不需要验证
//      .antMatchers("/user**").hasRole("USER")
//      .antMatchers("/admin**").hasRole("ADMIN")
      .anyRequest().hasRole("ANY")
        .withObjectPostProcessor(new ObjectPostProcessor[FilterSecurityInterceptor](){
          override def postProcess[O <: FilterSecurityInterceptor](o: O): O = {
            o.setAccessDecisionManager(memberAccessDecisionManager)
            o.setSecurityMetadataSource(MemberSecurityMetadataSource)
            o
          }
        })
      .and()
      .formLogin()//使用form表单登录
      .and()
      .sessionManagement()
      .maximumSessions(1)
//      .maxSessionsPreventsLogin(true)
      .expiredUrl("/")
      .and()
      .and()
      .logout()
      .logoutUrl("/logout")
      .and()
      .csrf().disable()
      .httpBasic().realmName("TEST").authenticationEntryPoint(RestAuthenticationEntryPoint)
  }

}
